<template>
  <div class="order-list-page">
    <div class="container py-4">
      <!-- 订单状态过滤 -->
      <div class="order-filters mb-4">
        <div class="card">
          <div class="card-body">
            <div class="row align-items-center">
              <div class="col-md-8">
                <ul class="nav nav-pills">
                  <li class="nav-item">
                    <a 
                      class="nav-link" 
                      :class="{ active: currentStatus === '' }"
                      @click="setStatus('')"
                    >
                      全部订单
                    </a>
                  </li>
                  <li class="nav-item">
                    <a 
                      class="nav-link" 
                      :class="{ active: currentStatus === 'pending' }"
                      @click="setStatus('pending')"
                    >
                      待付款
                    </a>
                  </li>
                  <li class="nav-item">
                    <a 
                      class="nav-link" 
                      :class="{ active: currentStatus === 'paid' }"
                      @click="setStatus('paid')"
                    >
                      待发货
                    </a>
                  </li>
                  <li class="nav-item">
                    <a 
                      class="nav-link" 
                      :class="{ active: currentStatus === 'shipped' }"
                      @click="setStatus('shipped')"
                    >
                      待收货
                    </a>
                  </li>
                  <li class="nav-item">
                    <a 
                      class="nav-link" 
                      :class="{ active: currentStatus === 'completed' }"
                      @click="setStatus('completed')"
                    >
                      已完成
                    </a>
                  </li>
                </ul>
              </div>
              <div class="col-md-4 text-end">
                <div class="input-group">
                  <input
                    type="text"
                    class="form-control"
                    placeholder="搜索订单号..."
                    v-model="searchKeyword"
                    @keyup.enter="searchOrders"
                  >
                  <button class="btn btn-outline-primary" @click="searchOrders">
                    <i class="fas fa-search"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单列表 -->
      <div class="order-list">
        <!-- 加载状态 -->
        <div v-if="loading" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2 text-muted">正在加载订单数据...</p>
        </div>

        <!-- 订单卡片 -->
        <div v-else-if="orders.length > 0">
          <div 
            class="order-item card mb-3"
            v-for="order in orders"
            :key="order.id"
          >
            <div class="card-header d-flex justify-content-between align-items-center">
              <div class="order-header-left">
                <span class="order-no fw-bold">订单号：{{ order.orderNo }}</span>
              </div>
              <div class="order-status">
                <span 
                  class="badge"
                  :class="getStatusClass(order.status)"
                >
                  {{ getStatusText(order.status) }}
                </span>
              </div>
            </div>
            
            <div class="card-body">
              <div class="row">
                <div class="col-md-8">
                  <div class="order-products">
                    <!-- 这里显示订单商品，实际应该从orderItems获取 -->
                    <div class="d-flex align-items-center mb-2">
                      <i class="fas fa-box me-2 text-muted"></i>
                      <span>共 {{ getTotalProductCount(order) }} 件商品</span>
                    </div>
                  </div>
                </div>
                <div class="col-md-4 text-end">
                  <div class="order-amount mb-2">
                    <span class="text-muted">实付金额：</span>
                    <span class="text-danger fw-bold h6">{{ formatPrice(order.totalPay) }}</span>
                  </div>
                  <div class="order-actions">
                    <button 
                      v-if="order.status === 'pending'"
                      class="btn btn-primary btn-sm me-2"
                      @click="payOrder(order)"
                    >
                      立即付款
                    </button>
                    <button 
                      v-if="order.status === 'shipped'"
                      class="btn btn-success btn-sm me-2"
                      @click="confirmReceipt(order)"
                    >
                      确认收货
                    </button>
                    <button 
                      v-if="order.status === 'pending'"
                      class="btn btn-outline-secondary btn-sm me-2"
                      @click="cancelOrder(order)"
                    >
                      取消订单
                    </button>
                    <button 
                      class="btn btn-outline-primary btn-sm"
                      @click="viewOrderDetail(order)"
                    >
                      查看详情
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 无订单数据 -->
        <div v-else class="empty-orders text-center py-5">
          <i class="fas fa-clipboard-list fa-4x text-muted mb-4"></i>
          <h4 class="mb-3">暂无订单</h4>
          <p class="text-muted mb-4">您还没有任何订单记录</p>
          <router-link to="/products" class="btn btn-primary">
            <i class="fas fa-shopping-cart me-2"></i>
            立即购物
          </router-link>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper text-center mt-4" v-if="totalPages > 1">
        <nav>
          <ul class="pagination justify-content-center">
            <li class="page-item" :class="{ disabled: currentPage === 1 }">
              <a class="page-link" @click="changePage(currentPage - 1)">
                <i class="fas fa-chevron-left"></i>
              </a>
            </li>
            <li 
              class="page-item" 
              :class="{ active: page === currentPage }"
              v-for="page in visiblePages" 
              :key="page"
            >
              <a class="page-link" @click="changePage(page)">{{ page }}</a>
            </li>
            <li class="page-item" :class="{ disabled: currentPage === totalPages }">
              <a class="page-link" @click="changePage(currentPage + 1)">
                <i class="fas fa-chevron-right"></i>
              </a>
            </li>
          </ul>
        </nav>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { Message } from '@/utils/message'

// 导入订单API
import { getUserOrders, updateOrderStatus, getOrderItems } from '@/api/order'
import type { Order, OrderItem } from '@/types/order'

const router = useRouter()
const userStore = useUserStore()

// 页面状态
const loading = ref(false)
const currentStatus = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 订单数据
const orders = ref<Order[]>([])
const totalOrders = ref(0)

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(totalOrders.value / pageSize.value)
})

const visiblePages = computed(() => {
  const total = totalPages.value
  const current = currentPage.value
  const delta = 2
  
  let start = Math.max(1, current - delta)
  let end = Math.min(total, current + delta)
  
  const pages = []
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 格式化价格
const formatPrice = (price: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(price)
}

// 获取订单状态样式
const getStatusClass = (status: string) => {
  const statusClasses = {
    'pending': 'bg-warning',
    'paid': 'bg-info',
    'shipped': 'bg-primary',
    'completed': 'bg-success',
    'cancelled': 'bg-secondary'
  }
  return statusClasses[status as keyof typeof statusClasses] || 'bg-secondary'
}

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusTexts = {
    'pending': '待付款',
    'paid': '待发货',
    'shipped': '待收货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusTexts[status as keyof typeof statusTexts] || '未知状态'
}

// 获取订单列表
const fetchOrders = async () => {
  if (!userStore.userInfo?.username) {
    router.push('/login')
    return
  }

  loading.value = true
  try {
    const response = await getUserOrders(
      userStore.userInfo.username,
      currentStatus.value,
      currentPage.value,
      pageSize.value
    )
    
    orders.value = response.data.records
    totalOrders.value = response.data.total
    
    // 为每个订单获取订单项信息
    await Promise.all(
      orders.value.map(async (order) => {
        try {
          const orderItemsResponse = await getOrderItems(order.id)
          order.orderItems = orderItemsResponse.data
        } catch (error) {
          console.error(`获取订单 ${order.id} 的订单项失败:`, error)
          order.orderItems = []
        }
      })
    )
  } catch (error) {
    console.error('获取订单列表失败:', error)
    Message.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 设置订单状态过滤
const setStatus = (status: string) => {
  currentStatus.value = status
  currentPage.value = 1
  fetchOrders()
}

// 搜索订单
const searchOrders = () => {
  currentPage.value = 1
  fetchOrders()
}

// 分页切换
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    fetchOrders()
  }
}

// 支付订单
const payOrder = async (order: Order) => {
  try {
    // 这里应该集成支付接口
    Message.success('支付功能待实现')
  } catch (error) {
    console.error('支付失败:', error)
    Message.error('支付失败')
  }
}

// 确认收货
const confirmReceipt = async (order: Order) => {
  try {
    await updateOrderStatus(order.id, 'completed')
    Message.success('确认收货成功')
    fetchOrders() // 刷新订单列表
  } catch (error) {
    console.error('确认收货失败:', error)
    Message.error('确认收货失败')
  }
}

// 取消订单
const cancelOrder = async (order: Order) => {
  try {
    await updateOrderStatus(order.id, 'cancelled')
    Message.success('订单已取消')
    fetchOrders() // 刷新订单列表
  } catch (error) {
    console.error('取消订单失败:', error)
    Message.error('取消订单失败')
  }
}

// 查看订单详情
const viewOrderDetail = (order: Order) => {
  router.push(`/orders/${order.id}`)
}

// 计算订单商品总数量
const getTotalProductCount = (order: Order) => {
  if (!order.orderItems || order.orderItems.length === 0) {
    return 0
  }
  return order.orderItems.reduce((total, item) => total + item.count, 0)
}

// 监听用户登录状态
watch(() => userStore.isLoggedIn, (isLoggedIn) => {
  if (!isLoggedIn) {
    router.push('/login')
  }
})

onMounted(() => {
  if (userStore.isLoggedIn) {
    fetchOrders()
  } else {
    router.push('/login')
  }
})
</script>

<style scoped>
.order-list-page {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.order-filters .nav-pills .nav-link {
  border-radius: 20px;
  margin-right: 10px;
  color: #6c757d;
  border: 1px solid #dee2e6;
  background: white;
}

.order-filters .nav-pills .nav-link.active {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

.order-item {
  transition: all 0.3s ease;
}

.order-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-no {
  font-family: 'Courier New', monospace;
}

.order-actions .btn {
  margin-left: 8px;
}

.empty-orders {
  background: white;
  border-radius: 10px;
  margin: 20px 0;
}

.pagination .page-link {
  border-radius: 6px;
  margin: 0 2px;
  border: 1px solid #dee2e6;
}

.pagination .page-item.active .page-link {
  background-color: #007bff;
  border-color: #007bff;
}
</style> 